import Dialog from '@vant/weapp/dialog/dialog';
const db = wx.cloud.database()
const storedata = db.collection('shoppingcar');

Page({
  data: {
    menuButtonTop: 0,
    menuButtonRight: 0,
    storelist: [],       // 购物车数据
    selectedIds: [],     // 选中商品的_id集合
    selectAll: false,    // 全选状态
    totalPrice: 0,
    checked: false,      // 总价
    isShowList:false
  },

  // 数量增减处理
  handleQuantity(e) {
    const { type, index } = e.currentTarget.dataset;
    const { storelist } = this.data;
    const item = storelist[index];
    this.setData({
        checked: e.detail,
      });
    if (type === 'add') {
      item.quantity += 1;
    } else if (type === 'minus' && item.quantity > 1) {
      item.quantity -= 1;
    }

    this.setData({
      storelist: [...storelist]
    }, () => {
      this.calculateTotal();  // 更新后自动计算总价
      this.updateCloudData(item); // 可选：同步到云数据库
    });
  },

  // 更新云数据（可选）
  updateCloudData(item) {
    storedata.doc(item._id).update({
      data: {
        quantity: item.quantity
      }
    });
  },

  // 单个商品选中状态变化
  onChange(e) {
    const { name } = e.currentTarget.dataset;
    const { selectedIds } = this.data;
    
    // 创建新数组保证响应式更新
    const newSelectedIds = [...selectedIds]; 
    const index = newSelectedIds.indexOf(name);
  
    if (index === -1) {
      newSelectedIds.push(name);
    } else {
      newSelectedIds.splice(index, 1);
    }
  
    this.setData({
      selectedIds: newSelectedIds, // 设置新数组
      selectAll: newSelectedIds.length === this.data.storelist.length
    }, this.calculateTotal);
  },

  // 全选/取消全选
  toggleSelectAll() {
    const { selectAll, storelist } = this.data;
    const newSelectAll = !selectAll;
    
    this.setData({
      selectAll: newSelectAll,
      selectedIds: newSelectAll ? storelist.map(item => item._id) : []
    }, this.calculateTotal);
  },

  // 计算总价
  calculateTotal() {
    const { storelist, selectedIds } = this.data;
    const total = storelist.reduce((sum, item) => {
      return selectedIds.includes(item._id) 
        ? sum + (item.price * item.quantity) 
        : sum;
    }, 0);
    
    this.setData({ totalPrice: total });
  },
  gotobuyflower(){
      wx.navigateTo({
        url: '/pages/Buyflowers/Buyflowers',
      })
  },
 
  // 执行删除操作
  deleteItem(event) {
    
      const { position, instance } = event.detail;
    const { index } = event.currentTarget.dataset;
    const { storelist, selectedIds } = this.data;
    const deletedItem = storelist.splice(index, 1)[0];
    
    // 从选中列表移除
   
    Dialog.confirm({
        message: '确定删除吗？',
      }).then(() => {
        const newSelected = selectedIds.filter(id => id !== deletedItem._id);
        this.setData({
            storelist: [...storelist],
            selectedIds: newSelected,
            selectAll: newSelected.length === storelist.length
          }, () => {
            this.calculateTotal();
            storedata.doc(deletedItem._id).remove(); // 同步删除云数据
            if (this.data.storelist.length === 0) {
                this.setData({
                  isShowList: true // 显示提示
                });
              }
      })
        
        // instance.close();
      })
      
    
  },
  onShow() {
    const { top, right } = wx.getMenuButtonBoundingClientRect();
    this.setData({ menuButtonTop: top, menuButtonRight: right });
    storedata.where({}).get().then(res => {
      const data = res.data.map(item => ({
        ...item,
        quantity: item.quantity || 1 // 确保有quantity字段
      }));
      this.setData({ storelist: data.reverse() ,isShowList: data.length === 0});
    });
    if(this.data.storelist.length === 0 ){
        this.setData({
            isShowList: false
        })
    }
  },
  gotoOrder() {
    const { storelist, selectedIds } = this.data;
    
    if (selectedIds.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
  
    // 1. 获取选中商品
    const selectedItems = storelist.filter(item => 
      selectedIds.includes(item._id)
    );
  
    // 2. 编码数据
    const encodedData = encodeURIComponent(JSON.stringify(selectedItems));
    
    // 3. 删除云数据库记录
    const deletePromises = selectedIds.map(id => 
      storedata.doc(id).remove()
    );
  
    Promise.all(deletePromises).then(() => {
      // 4. 更新本地数据
      const newStorelist = storelist.filter(item => 
        !selectedIds.includes(item._id)
      );
      
      this.setData({
        storelist: newStorelist,
        selectedIds: [],
        selectAll: false,
        totalPrice: 0
      });
  
      // 5. 跳转页面
      wx.navigateTo({
        url: `/pages/SubmitOrder/SubmitOrder?items=${encodedData}`
      });
    }).catch(err => {
      console.error('删除失败:', err);
      wx.showToast({
        title: '订单提交失败',
        icon: 'none'
      });
    });
  }

});